﻿#region Imports
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using PlayRandom.ViewModels;
#endregion Imports

namespace PlayRandom
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        #region Constructors
        public App()
            : base()
        {
            Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        #endregion Constructors

        #region Methods
        private void Application_Exit(object sender, ExitEventArgs e)
        {
            MainViewModel.SaveSettings();
        }

        void CurrentDomain_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LogUnhandledError(e.Exception);
            e.Handled = true;

            Application.Current.Shutdown();
        }

        private static void LogUnhandledError(Exception ex)
        {
            StackTrace trace = new StackTrace(ex, true);
            StackFrame frame = trace.GetFrame(1);

            var msg = String.Format("File\t{0}\nMethod\t{1}\nLine\t{2}, {3}", Path.GetFileNameWithoutExtension(frame.GetFileName()), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
            MessageBox.Show(String.Format("{0}\n\n{1}", ex.Message, msg), "Unhandled exception..");
        }
        #endregion Methods
    }
}
